#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>

#define SERV_PORT 8888

int main(int argc, char **argv) {
    if (argc != 2) {
        fprintf(stderr, "usage: tcpclient <IPaddress>\n");
        exit(1);
    }

    int socket_fd;
    socket_fd = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in server_addr;
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(SERV_PORT);
    inet_pton(AF_INET, argv[1], &server_addr.sin_addr);

    socklen_t server_len = sizeof(server_addr);
    int connect_rt = connect(socket_fd, (struct sockaddr *) &server_addr, server_len);
    if (connect_rt < 0) {
        perror("connect failed ");
        exit(1);
    }

    char *message = "Hello, World!";
    uint32_t message_length = htonl(strlen(message));

    if (send(socket_fd, &message_length, sizeof(message_length), 0) < 0) {
        perror("send message_length failure");
        exit(1);
    }

    if (send(socket_fd, message, strlen(message), 0) < 0) {
        perror("send message failure");
        exit(1);
    }

    close(socket_fd);
    exit(0);
}
